<template>
  <div class="operateProduct">
    <div class="head">
      产品管理》{{type}}
    </div>
    <div class="formContent">
      <el-form :label-position="labelPosition" label-width="20%" :model="formLabelAlign">
        <el-form-item label="产品名称（中文）">
          <el-input v-model="formLabelAlign.chinaName"></el-input>
          <el-button class="goManageProduct" @click="goBackManageProduct">返回</el-button>
        </el-form-item>
        <el-form-item label="产品名称（英文）">
          <el-input v-model="formLabelAlign.englishName"></el-input>
        </el-form-item>
        <el-form-item label="展示图">
          <el-image class="showImg" :src="formLabelAlign.coverIcon" fit="fill" @click="uploadFile(0)"></el-image>
          <div class="tips showImgtips" v-if="isAdd">
              <div>W：216像素</div><div>H：260像素</div>           
            </div>
        </el-form-item>
        <el-form-item label="详情图">
          <el-image class="showImg"  :src="formLabelAlign.detailIcon" fit="fill" @click="uploadFile(1)"></el-image>
          <div class="tips detailImgtips" v-if="isAdd">
              <div>W：630像素</div>
              <div>H：990像素</div>           
            </div>
        </el-form-item>
        <el-form-item label="所属一级分类">
          <el-select v-model="formLabelAlign.classOneId" placeholder="请选择" @visible-change='getAllClassOne'>
            <el-option v-for="item in formLabelAlign.classLevel1Options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属二级分类">
          <el-select v-model="formLabelAlign.classTwoId" placeholder="请选择" @visible-change='getAllClassTwo'>
            <el-option v-for="item in formLabelAlign.classLevel2Options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传数据文件">
          <el-image class="updateImg" :src="formLabelAlign.url" fit="fill"></el-image>
          <el-upload class="upload-demo uploadFile" action="111" :before-upload="handleFile" :limit="2" :file-list="fileList">
            <el-button class="updateBtn" size="small" >{{btnText}}</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
          <!-- <el-button class="updateBtn" @click="uploadFile(2)">{{btnText}}</el-button> -->
        </el-form-item>
      </el-form>
       <!-- 上传组件 -->
      <el-upload style="position:absolute;top:0;left:23%;opacity:0;"   class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/" :on-success="handleAvatarSuccess" :on-exceed='exceedList' :before-upload="handlePreview" :limit="1">
        <el-button ref="uploadBtn" class="uploadBtn" size="small" type="primary">点击上传</el-button>
      </el-upload>
      <div>
        <el-button class="submitBtn" @click="product">确定</el-button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'operateProduct',
  data () {
    return {
      type:'',//操作类型
      id:"",//编辑时操作行的id
      labelPosition: 'left',
      formLabelAlign: {//表单数据
          chinaName: '',
          englishName: '',
          coverIcon:require('../assets/img/logo1.png'),
          coverIconkey:"",
          detailIcon:require('../assets/img/logo1.png'),
          detailIconkey:"",
          classOneId:'',
          classLevel1Options:[],
          classTwoId:'',
          classLevel2Options: [],
          url:require('../assets/img/logo1.png'),
          file:"",//上传的文件
          fileKey:"",
          fileName:"",//上传的文件名称
        },
      btnText:'',//按钮文字
      uploadType:"",//上传什么内容，0是展示图，1是详情图，2是上传文件
      fileList:[],//上传文件
      isAdd:true,//新增显示图片tips
    }
  },
  mounted(){
    let _this = this;
    _this.type = _this.$route.params.type == 'add'?'新增':'编辑';
    _this.btnText = _this.$route.params.type == 'add'?'+':'更换';
    // _this.isAdd = _this.$route.params.type == 'add'?true:false;

    _this.id = _this.$route.params.id;//获取操作行的id
    _this.getAllClassOne(true);
    _this.getAllClassTwo(true);
    if(_this.id >= 0){
      _this.getProductInfo();//编辑信息，获取产品信息详情
    }
    
    // _this.formLabelAlign.classLevel1Options = _this.$store.state.classOneOptions;//获取所有第一分类
    // _this.formLabelAlign.classLevel2Options = _this.$store.state.classTwoOptions;//获取所有二级分类
  },
  methods:{
    //返回产品管理
    goBackManageProduct(){
      let _this = this;
      _this.$router.push({
        path:'/manageProduct'
      });
    },
    //上传文件：模拟上传文件按钮的点击事件
    uploadFile(uploadType){
      let _this = this;
      ////console.log(_this.$refs.uploadBtn);
      // _this.$refs.uploadBtn.click();
      document.getElementsByClassName('uploadBtn')[0].click();
      _this.uploadType = uploadType;//获取上传什么文件
    },
    //上传文件之前的钩子函数
    // handlePreview(file) {
    //   ////console.log('上传文件',file);
    //   let _this = this;
    //   let fd = new FormData();
    //   fd.append('file',file);//传文件
    //   let sessionId = _this.$store.state.id;//获取token
    //   let suffix = file.name.split('.')[1];
    //   ////console.log(suffix,'suffix');
    //   let contentType = file.type;
    //   let api = '/api/base/app/getOSSUploadUrl/{suffix}?contentType='+contentType;
    //   _this.axios.get(api,{
    //         params:fd,
    //         headers:{
    //           sessionId,
    //         }
    //     })
    //   .then(function (res) {      
    //       ////console.log('上传文件2',res);
    //       if(_this.uploadType == 0){
    //         _this.formLabelAlign.coverIcon  = res.data.data.bussData.downloadUrl;
    //         _this.formLabelAlign.coverIconkey = res.data.data.bussData.fileKey;
    //       }
    //       else if(_this.uploadType == 1){
    //         _this.formLabelAlign.detailIcon  = res.data.data.bussData.downloadUrl;
    //         _this.formLabelAlign.detailIconkey = res.data.data.bussData.fileKey;

    //       }
    //       else if(_this.uploadType == 2){//上传文件
    //          _this.formLabelAlign.file  = res.data.data.bussData.downloadUrl;
    //           _this.formLabelAlign.fileKey = res.data.data.bussData.fileKey;
    //       }
    //   })
    //   .catch(function (error) {
    //     ////console.log('上传错误2',error);
    //   })
    //   return false//屏蔽了action的默认上传
    // },
    //上传图片之前的钩子函数
    handlePreview(file) {
      ////console.log('上传文件',file);
      let _this = this;
      
      let sessionId = _this.$store.state.id;//获取token

      let suffix = file.name.split('.')[1];
      ////console.log(suffix,'suffix');
      let contentType = file.type;
      ////console.log('contentType',contentType);
      if(_this.uploadType == 0 || _this.uploadType == 1){
        if(contentType.indexOf('image')<0){
          _this.$message('请上传图片');
          return
        }
      }
      
      let api = '/api/base/app/getOSSUploadFormData/'+suffix;
      _this.axios.get(api,{
            headers:{
              sessionId,
            }
        })
      .then(function (res) {      
          ////console.log('上传文件',res);
          if(res.data.code == 401){
            _this.$message({
              type: 'info',
              message: '登录已失效，请重新登录'
            });  
            _this.$router.push({
              path:"/"
            });
            return
          }
          let key = res.data.data.bussData.fileKey;
          // _this.form.iconKey = res.data.data.bussData.fileKey;
          // _this.form.icon  = res.data.data.bussData.downloadUrl;
          let uploadUrl = res.data.data.bussData.uploadUrl;
          let downloadUrl = res.data.data.bussData.downloadUrl;
          let uploadFormData = res.data.data.bussData.formData;
          let fd = new FormData();
          fd.append('OSSAccessKeyId',uploadFormData.OSSAccessKeyId);//传文件
          fd.append('signature',uploadFormData.signature);//传文件
          fd.append('success_action_status',uploadFormData.success_action_status);//传文件
          fd.append('key',uploadFormData.key);//传文件
          fd.append('policy',uploadFormData.policy);//传文件
          fd.append('file',file);//传文件
          _this.axios.post(uploadUrl,fd).then(res=>{
            ////console.log('第二步上传',res);
            if(res.status == 200){
              if(_this.uploadType == 0){
                _this.formLabelAlign.coverIcon  = downloadUrl;
                _this.formLabelAlign.coverIconkey = key;
              }
              else if(_this.uploadType == 1){
                _this.formLabelAlign.detailIcon  = downloadUrl;
                _this.formLabelAlign.detailIconkey = key;
              }
              else if(_this.uploadType == 2){
                _this.formLabelAlign.file  = downloadUrl;
                _this.formLabelAlign.fileKey = key;
              }
              
            }else{
              _this.$message({
              type: 'info',
              message: '上传失败，请重新上传'
            });  
            }
          }).catch(err=>{
            //console.log('第二步上传错误',err);
            if(_this.uploadType == 0){
                _this.formLabelAlign.coverIcon  = downloadUrl;
                _this.formLabelAlign.coverIconkey = key;
              }
              else if(_this.uploadType == 1){
                _this.formLabelAlign.detailIcon  = downloadUrl;
                _this.formLabelAlign.detailIconkey = key;
              }
              else if(_this.uploadType == 2){
                _this.formLabelAlign.file  = downloadUrl;
                _this.formLabelAlign.fileKey = key;
              }
            
          });
      })
      .catch(function (error) {
        ////console.log('上传错误',error);
      })
      return false//屏蔽了action的默认上传
    },
    //上传文件之前的钩子函数
    handleFile(file) {
      ////console.log('上传文件',file);
      let _this = this;
      console.log(_this.fileList.length)
      if(_this.fileList.length > 0){
        _this.$message('只允许上传一个文件，请先移除已上传的文件');
        return
      }
      let sessionId = _this.$store.state.id;//获取token

      let suffix = file.name.split('.')[1];
      ////console.log(suffix,'suffix');
      let contentType = file.type;
      ////console.log('contentType',contentType);
      
      
      let api = '/api/base/app/getOSSUploadFormData/'+suffix;
      _this.axios.get(api,{
            headers:{
              sessionId,
            }
        })
      .then(function (res) {      
          ////console.log('上传文件',res);
          if(res.data.code == 401){
            _this.$message({
              type: 'info',
              message: '登录已失效，请重新登录'
            });  
            _this.$router.push({
              path:"/"
            });
            return
          }
          let key = res.data.data.bussData.fileKey;
          // _this.form.iconKey = res.data.data.bussData.fileKey;
          // _this.form.icon  = res.data.data.bussData.downloadUrl;
          let uploadUrl = res.data.data.bussData.uploadUrl;
          let downloadUrl = res.data.data.bussData.downloadUrl;
          let uploadFormData = res.data.data.bussData.formData;
          let fd = new FormData();
          fd.append('OSSAccessKeyId',uploadFormData.OSSAccessKeyId);//传文件
          fd.append('signature',uploadFormData.signature);//传文件
          fd.append('success_action_status',uploadFormData.success_action_status);//传文件
          fd.append('key',uploadFormData.key);//传文件
          fd.append('policy',uploadFormData.policy);//传文件
          fd.append('file',file);//传文件
          _this.axios.post(uploadUrl,fd).then(res=>{
            ////console.log('第二步上传',res);
            if(res.status == 200){
              _this.formLabelAlign.file  = downloadUrl;
              _this.formLabelAlign.fileKey = key;
              _this.formLabelAlign.fileName = file.name;
              
            }else{
              _this.$message({
              type: 'info',
              message: '上传失败，请重新上传'
            });  
            }
          }).catch(err=>{
            //console.log('第二步上传错误',err);
            _this.formLabelAlign.file  = downloadUrl;
            _this.formLabelAlign.fileKey = key;
            _this.formLabelAlign.fileName = file.name;
            let obj = {
              'name':file.name,
              'url': _this.formLabelAlign.file,
            }
            _this.fileList.splice(0,1,obj);
            
          });
      })
      .catch(function (error) {
        ////console.log('上传错误',error);
      })
      return false//屏蔽了action的默认上传
    },
    //上传文件超出钩子函数
    exceedList(files, fileList){
      this.$message.warning(`当前限制选择 1 个文件,请先移除之前上传的文件`);

    },
    //图片上传成功实现本地预览
    handleAvatarSuccess(res, file) {
      let _this = this;
      ////console.log('上传成功的函数');
      // if(_this.uploadType == 0){
      //   _this.formLabelAlign.coverIcon  = URL.createObjectURL(file.raw);
      // }
      // else if(_this.uploadType == 1){
        
      // }
      // else if(_this.uploadType == 2){//上传文件
        
      // }
      
    },
    //操作产品：新增或编辑
    product(){
      let _this = this;
      if(_this.formLabelAlign.chinaName == ''){
        _this.$message('请先填写产品的中文名称');
        return
      }
      if(_this.formLabelAlign.englishName == ''){
        _this.$message('请先填写产品的英文名称');
        return
      }
      if(_this.formLabelAlign.coverIcon == require('../assets/img/logo.png')){
        _this.$message('请先点击图片上传展示图');
        return
      }
      if(_this.formLabelAlign.detailIcon == require('../assets/img/logo.png')){
        _this.$message('请先点击图片上传详情图');
        return
      }
      if(_this.formLabelAlign.classOneId == ''){
        _this.$message('请先选择所属的一级分类');
        return
      }
      if(_this.formLabelAlign.classTwoId == ''){
        _this.$message('请先选择所属的二级分类');
        return
      }
      if(_this.formLabelAlign.file == ''){
        _this.$message('请先上传文件');
        return
      }
      // if(_this.formLabelAlign.detailIcon == require('../assets/img/logo.png')){
      //   _this.$message('请先上传详情图');
      //   return
      // }
      let api = '';
      let data = '';//传参
      let sessionId = _this.$store.state.id;//获取token
      if(_this.type == '新增'){
        api = '/api/product/insert';
        data ={
            "chinaName": _this.formLabelAlign.chinaName,
            "classOneId": _this.formLabelAlign.classOneId,
            "classTwoId": _this.formLabelAlign.classTwoId,
            "coverIcon": _this.formLabelAlign.coverIconkey,
            "detailIcon": _this.formLabelAlign.detailIconkey,
            "englishName": _this.formLabelAlign.englishName,
            "file": _this.formLabelAlign.fileKey,
            "fileName": _this.formLabelAlign.fileName,
          }
        
      }else{//编辑
        api = '/api/product/update';
        data = {
          "chinaName": _this.formLabelAlign.chinaName,
          "classTwoId": _this.formLabelAlign.classTwoId,
          "coverIcon": _this.formLabelAlign.coverIconkey,
          "detailIcon": _this.formLabelAlign.detailIconkey,
          "englishName": _this.formLabelAlign.englishName,
          "file": _this.formLabelAlign.fileKey,
          "id": _this.id,
          "classOneId": _this.formLabelAlign.classOneId,
          "fileName": _this.formLabelAlign.fileName,
        };
      }
      _this.axios.post(api,data,{
        headers:{
          sessionId
        }
      }).then(res=>{
        ////console.log('操作产品',res);
        if(res.data.code == 401){
          _this.$message({
            type: 'info',
            message: '登录已失效，请重新登录'
          });  
          _this.$router.push({
            path:"/"
          });
          return
        }
        
        if(res.data.code == 200){
          _this.$message({
            type: 'success',
            message: _this.type+'成功！'
          }); 
          _this.formLabelAlign.chinaName = '';//清空字段
          _this.formLabelAlign.englishName = '';//清空字段
          _this.formLabelAlign.coverIcon = '';//清空字段
          _this.formLabelAlign.coverIconkey = '';//清空字段
          _this.formLabelAlign.detailIcon = '';//清空字段
          _this.formLabelAlign.detailIconkey = '';//
          _this.formLabelAlign.classOneId = '';//清空字段
          _this.formLabelAlign.classTwoId = '';//清空字段
          _this.formLabelAlign.file = '';//清空字段
          _this.formLabelAlign.fileKey = '';//清空字段
          _this.$router.push({
            path:"/manageProduct"
          });
        }
      });
    },
    //编辑信息时初始化时获取信息详情
    getProductInfo(){
      let _this = this;
      let api = '/api/product/find_detail?id='+_this.id;
      let sessionId = _this.$store.state.id;//获取token
      _this.axios({
        url:api,
        method: 'post',
        headers:{
          sessionId,
        }		
      }).then(res=>{
        ////console.log('编辑初始化产品信息',res);
        if(res.data.code == 401){
            _this.$message({
              type: 'info',
              message: '登录已失效，请重新登录'
            });  
            _this.$router.push({
              path:"/"
            });
            return
          }
        if(res.data.code == 200){
          // _this.formLabelAlign.chinaName = '';//清空字段
          // _this.formLabelAlign.englishName = '';//清空字段
          // _this.formLabelAlign.coverIcon = '';//清空字段
          // _this.formLabelAlign.detailIcon = '';//
          // _this.formLabelAlign.classOneId = '';//清空字段
          // _this.formLabelAlign.classTwoId = '';//清空字段
          // _this.formLabelAlign.file = '';//清空字段
          _this.formLabelAlign = res.data.data.bussData;
          _this.formLabelAlign.url = require('../assets/img/logo.png');//上传文件前面的图片路径，设置默认路径
          // _this.formLabelAlign.classLevel1Options = _this.$store.state.classOneOptions;//获取所有第一分类
          // _this.formLabelAlign.classLevel2Options = _this.$store.state.classTwoOptions;//获取所有二级分类
        }
      });
    },
    // //获取所有一级分类
    getAllClassOne(isShow){
      let _this = this;
      ////console.log(isShow,'下拉框是否出现');
      if(!isShow){
        return
      }
      let api = '/api/sysClassOne/find_list';
      let optionsOne = [];//清空   
      let sessionId = _this.$store.state.id;//获取token 
      _this.axios({
            url:api,
            method: 'post',
            headers:{
              sessionId,
            }		
  			}).then(res=>{
        ////console.log('查询所有的一级分类',res)
             
        let class1 = res.data.data.bussData;
        class1.forEach(item=>{
          let obj = {};
          obj.value = item.id;
          obj.label = item.chinaName;
          optionsOne.push(obj);
          // _this.form.class1Options.push(obj);
        });
        // ////console.log('optionsOne',optionsOne);
        optionsOne = optionsOne.filter(item=>{
          return item.label != '全部'
        });
        _this.$store.dispatch('saveClassOne',optionsOne);//缓存所有一级分类
        // _this.formLabelAlign.classLevel1Options =[];
        _this.formLabelAlign.classLevel1Options = _this.$store.state.classOneOptions;//获取所有第一分类
        let obj = {
          value:"",
          label:"全部",
        }

        _this.formLabelAlign.classLevel1Options.unshift(obj);
        _this.formLabelAlign.classTwoId = '';
        // _this.getAllClassTwo(true);
        ////console.log('saveClassOne',optionsOne,_this.$store.state.classOneOptions);


      });
    },
    //获取所有二级分类
    getAllClassTwo(isShow){
      let _this = this;
      //console.log(isShow,'下拉框是否出现');
      if(!isShow){
        return
      }
      //console.log('加载前的_this.formLabelAlign.classLevel2Options',_this.formLabelAlign.classLevel2Options);
      let api = '/api/sysClassTwo/find_list';
      let optionsTwo = [];//清空
      let sessionId = _this.$store.state.id;//获取token 
      _this.axios({
            url:api,
            method: 'post',
            headers:{
              sessionId,
            }		
  			}).then(res=>{
        //console.log('请求所有的二级分类',res);
        let class2 = res.data.data.bussData;
        //console.log('class2',class2);     
      //   // class2 = class2.filter(item=>{
      //   //   return item.label != '全部'
      //   // });
        _this.$store.dispatch('saveClassTwo',class2);//缓存所有二级分类
        
        //console.log('classTwoOptions',_this.$store.state.classTwoOptions);
      //   // _this.formLabelAlign.classLevel2Options =[];
        _this.formLabelAlign.classLevel2Options = _this.$store.state.classTwoOptions;//获取所有二级分类
        //console.log(' _this.formLabelAlign.classLevel2Options',_this.formLabelAlign.classLevel2Options);

        _this.formLabelAlign.classLevel2Options.forEach(item=>{
          // let obj = {};
          item.value = item.id;
          item.label = item.chinaName;
          // optionsTwo.push(obj);
        });
        let obj = {
          value:"",
          label:"全部",
        }

        _this.formLabelAlign.classLevel2Options.unshift(obj);
        //console.log(' _this.formLabelAlign.classLevel2Options',_this.formLabelAlign.classLevel2Options);
        var temp = [];
        if(_this.formLabelAlign.classOneId != '' && _this.formLabelAlign.classOneId != undefined){
          temp = _this.formLabelAlign.classLevel2Options.filter(item=>{
            //console.log(_this.formLabelAlign.classOneId,'_this.formLabelAlign.classOneId');
            return item.classOneId == _this.formLabelAlign.classOneId
          });
        }else{
          temp = _this.formLabelAlign.classLevel2Options.slice(0);
        }
        //console.log(temp,'temp');
         _this.formLabelAlign.classLevel2Options = [];
        temp.forEach((item,index)=>{
           _this.formLabelAlign.classLevel2Options.splice(index,1,item);
        });
        //  _this.formLabelAlign.classLevel2Options = temp.slice(0);
        //console.log('过滤后classTwoOptions',_this.formLabelAlign.classLevel2Options,_this.$store.state.classTwoOptions);
        _this.$forceUpdate();//视图强制更新


      });
    },
    
  },
  // computed:{
  //   classLevel2Options(){
  //     return this.formLabelAlign.classLevel2Options
  //   }
  // },
  // watch:{
  //   formLabelAlign:{
  //     deep:true,
  //     handler(val, oldVal){
  //       let _this = this;
  //       ////console.log(val,'监视formLabelAlign')
  //       // _this.formLabelAlign.classLevel2Options = val.classLevel2Options.filter((item,index)=>{
  //       //   ////console.log(_this.formLabelAlign.classOneId,index);
  //       //   return item.classOneId == _this.formLabelAlign.classOneId
  //       // });
  //       // ////console.log(val.classLevel2Options,'监视后classLevel2Options')
  //     }
  //   }
  // }
  
}
</script>

<style scoped>
/* 整体样式 */
.operateProduct{
  height: 94%;
  width: 94%;
  border: .0625rem solid rgba(187, 187, 187, 1);
  margin: 0 auto;
  position: relative;
  padding: 1%;
  font-size: .875rem;
  color:rgba(16, 16, 16, 1) !important;

}
/* 按钮 */
.operateProduct>>>button{
  color:rgba(16, 16, 16, 1) !important;
}
/* 表单 */
.operateProduct>>>.formContent{
  width: 80%;
  margin: 0 auto;
}
/* 输入框 */
.operateProduct>>>.formContent .el-input,.formContent .el-select{
  width: 30%;
} 
.operateProduct>>>.formContent .el-select .el-input{
  width: 100%;
}
/* 图片 */
.operateProduct>>>.formContent .el-image.showImg{
  width: 8%;
  position: absolute;
  left: 10%;
  height: 110%;
}
.operateProduct>>>.formContent .el-image.updateImg{
  width: 12%;
  position: absolute;
  top: 1%;
}
/* 弹框图片tips */
.operateProduct>>>.tips div{
  line-height: 1.2rem;
}
.operateProduct>>>.showImgtips{
  position: absolute;
  top: 14%;
  left: 20%;
}
.operateProduct>>>.detailImgtips{
  position: absolute;
  top: 14%;
  left: 20%;
}
/* 返回按钮 */
.operateProduct>>>.goManageProduct{
  position: absolute;
  top: 0%;
  left: 74%;
}
/* 更改按钮 */
/* .operateProduct>>>.updateBtn{
  position: absolute;
  top: 123%;
  left: 13%;
  padding: 0.5% 3%;
} */
/* 上传文件上传组件 */
.operateProduct>>>.uploadFile{
  position: absolute;
  top: 20%;
  left: 13%;
}
/* 提交表单按钮 */
.operateProduct>>>.submitBtn{
  position: absolute;
  top: 87%;
  left: 32%;
}
</style>
